package msb.class01;

import org.junit.Assert;
import org.junit.Test;
import common.util.ArrayUtil;

import java.util.Arrays;
import java.util.Random;

/**
 * 在有序数组中，是否存在一个数
 * <p>
 * 二分法
 */
public class Code04_BSExist {


    public static boolean exists(int[] arr, int num) {

        int L = 0;
        int R = arr.length - 1;
        int mid = 0;
        while (L < R) {
            mid = L + ((R - L) >> 1);
//            System.out.println("mid:" + mid);
            if (num == arr[mid]) {
                return true;
            }
            if (num < arr[mid]) {
                R = mid - 1;
            }
            if (num > arr[mid]) {
                L = mid + 1;
            }
//            System.out.println("L:" + L + ",R:" + R);
        }
        return num == arr[L];
    }

    public static boolean existsSimple(int[] arr, int num) {
        for (int i = 0; i < arr.length; i++) {
            if (num == arr[i]) {
                return true;
            }
        }
        return false;
    }


    @Test
    public void check() {
        int count = 10000;
        int fail = 0;
        for (int i = 0; i < count; i++) {
            Random random = new Random();
            int num = random.nextInt(100);
            int[] arr = ArrayUtil.instant(100, 100);
            Arrays.sort(arr);
            boolean exists = exists(arr, num);
            boolean existsSimple = existsSimple(arr, num);
            if (exists != existsSimple) {
                fail++;
                System.out.println("arr:" + Arrays.toString(arr));
                System.out.println("num:" + num);
                System.out.println("exists:" + exists + ",checkExists:" + existsSimple);
            }
        }
        Assert.assertEquals(0, fail);
    }

    @Test
    public void debug() {
        int[] arr = new int[]{1, 2, 3, 3, 4, 5, 6, 6, 7, 9};
        int num = 9;
        Assert.assertTrue(exists(arr, num));
    }

}
